/**
 * Created with IntelliJ IDEA.
 * User: zhenqin
 * Date: 13-9-9
 * Time: 上午9:42
 * To change this template use File | Settings | File Templates.
 */

var ws = null;
var port = 8010;
var context = "ztries";


function startWebSocketServer(host, dataId, openFunc, onMessageFunc, closeFunc) {
    // 设定WebSocket,注意协议是ws，请求是指向对应的WebSocketServlet的，
    // localhost:8080/web-socket是你实际web项目发布的地址，
    // 后面的/EchoServlet是在上面web.xml里配置的servlet访问的url</span>
    var url = "ws://" + host + ":" + port + "/" + context + "/websocket/" + dataId;
    // 创建WebSocket实例，chrome浏览器使用
    if ('WebSocket' in window) {
        ws = new WebSocket(url);
    } else {
        window.alert('You Web Browser Unsupported WebSocket.');
        return;
    }

    // WebSocket握手完成，连接成功的回调
    // 有个疑问，按理说new WebSocket的时候就会开始连接了，如果在设置onopen以前连接成功，是否还会触发这个回调
    if (openFunc == null) {
        openFunc = defaultOnOpen;
    }
    ws.onopen = openFunc;

    if (onMessageFunc == null) {
        onMessageFunc = onMessageCall;
    }
    // 收到服务器发送的文本消息, event.data表示文本内容
    ws.onmessage = onMessageFunc;

    if (closeFunc == null) {
        closeFunc = defaultOnClose;
    }
    // 关闭WebSocket的回调
    ws.onclose = closeFunc;
}

function defaultOnOpen() {
    console.log('WebSocket Opened!');
}

function onMessageCall(recv) {
    //window.alert('Receive message: ' + recv.data);
    //console.log(recv.data);
    var data = eval('(' + recv.data + ')');
    console.log(data.message);
    //var message = $("#showLogs").text() + "\n" + data.message;
    //$("#showLogs").text(message)
}

function defaultOnClose() {
    window.alert('WebSocket Closed!');
}
